// utils.js
import md5 from './md5.js';
const sdkObj = require('../config.js').tagObj;
const sdkName = require('../config.js').tagName;


//构建http请求
export function httpRequest(params) {  
    switch (sdkName) {  
        case 'my': {  
            let obj = {  
                ...params,  
                headers: params.header  
            };  
            delete obj.header;  
            return sdkObj.request(obj);  
        } 
		case 'jd': {
			return sdkObj.request({
			    ...params,
				header: {
					...(params.header || {}),
					'Accept': 'application/json', // 覆盖 Accept 字段
					'Content-Type': 'application/json', // 覆盖 Content-Type 字段
				},
			}); 
		}
        default:  
            return sdkObj.request({  
                ...params  
            });  
    }  
}

// 显示消息提示框
export function Toast(title, type, time, show) {
	switch(sdkName){
		case 'wx':
		case 'qq':
		sdkObj.showToast({
			title: title,
			icon: type,
			duration: time,
			mask: show
		})
		break;
		case 'my':
		sdkObj.showToast({
			content: title,
			type: type,
			duration: time,
			mask: show
		})
		break;
		case 'mt':
		case 'tt':
		sdkObj.showToast({
			title: title,
			icon: type,
			duration: time
		})
		default:
		sdkObj.showToast({
			title: title,
			icon: type,
			duration: time,
			mask: show
		})
	}
}

// 显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
export function Loading(title) {
	switch(sdkName){
		case 'wx':
		case 'qq':
		case 'mt':
		case 'tt':
		sdkObj.showLoading({
			title: title,
		})
		break;
		case 'my':
		sdkObj.showLoading({
			content: title,
		})
		break;
		default:
		sdkObj.showLoading({
			title: title,
		})
	}
}

// 显示模态对话框
export function Modal(title, content,showCancel=true,confirmText='确定') {
	return new Promise((resolve, reject) => {
		switch(sdkName){
			case 'wx':
			case 'qq':
			case 'mt':
			case 'tt':
			sdkObj.showModal({
				title: title || '',
				content: content,
				showCancel:showCancel,
				confirmText:confirmText,
				success: function(res) {
					if (res.confirm) {
						resolve(res.confirm);
					} else if (res.cancel) {
						resolve(res.cancel);
					}
				},
				fail: reject
			})
			break;
			case 'my':
			if(showCancel){
				sdkObj.confirm({
					title: title || '',
					content: content,
					confirmButtonText:confirmText,
					success: function(res) {
						if (res.confirm) {
							resolve(res.confirm);
						} else if (res.cancel) {
							resolve(res.cancel);
						}
					},
					fail: reject
				})
			}else{
				sdkObj.alert({
					title: title || '',
					content: content,
					buttonText:confirmText,
					success: function(res) {
						console.log(res)
						resolve(res);
					},
					fail: reject
				})
			}
			break;
			default:
			sdkObj.showModal({
				title: title || '',
				content: content,
				showCancel:showCancel,
				confirmText:confirmText,
				success: function(res) {
					if (res.confirm) {
						resolve(res.confirm);
					} else if (res.cancel) {
						resolve(res.cancel);
					}
				},
				fail: reject
			})
		}
	})
}

export function getLaunchOptionsSync() {
	return sdkObj.getLaunchOptionsSync()
}

export function getSystemInfo() {
	return new Promise((resolve, reject) => {
		sdkObj.getSystemInfo({
			success: (res) => {
				resolve(res);
			},
			fail: reject
		})
	})
}

//登录
export function login() {
	return new Promise((resolve, reject) => {
		switch(sdkName){
			case 'wx':
			case 'qq':
			case 'mt':
			case 'tt':
			sdkObj.login({
				success: (res) => {
					resolve(res.code);
				},
				fail: reject
			})
			break;
			case 'my':
			sdkObj.getAuthCode({
				scopes: ['auth_base'],
				success: (res) => {
					resolve(res.authCode);
				},
				fail: reject
			})
			break;
			default:
			sdkObj.login({
				success: (res) => {
					resolve(res.code);
				},
				fail: reject
			})
		}
		
	})
}

//创角获取头像信息的button
export function createUserInfoButton(){
	return new Promise((resolve, reject) => {
		let sysInfo = wx.getSystemInfoSync();
		let screenW = sysInfo.screenWidth;
		let screenH = sysInfo.screenHeight;
		let leftW = (screenW - 140) / 2;
		let topH = (screenH - 40) / 2;
		let background = '#07c160';
		const button = sdkObj.createUserInfoButton({
			type: 'text',
			text: '获取用户信息',
			style: {
				left: leftW,
				top: topH,
				width: 140,
				height: 40,
				lineHeight: 40,
				backgroundColor: background,
				color: '#ffffff',
				textAlign: 'center',
				fontSize: 14,
				borderRadius: 4
			}
		})
		button.onTap(userInfo => {
			console.log(userInfo)
			if(userInfo.errMsg=='getUserInfo:ok'){
				resolve (userInfo);
			}else{
				reject (userInfo)
			}
			button.destroy();
		})
	})
}

//检查登录态是否过期
export function checkSession() {
	return new Promise((resolve, reject) => {
		sdkObj.checkSession({
			success: (res) => {
				resolve(res);
			},
			fail: reject
		})
	})
}

//获取微信昵称头像等信息
export function authorize(scope) {
	return new Promise((resolve, reject) => {
		switch(sdkName){
			case 'wx':
			case 'qq':
			case 'mt':
			case 'tt':
			sdkObj.authorize({
				scope: scope,
				success: (res) => {
					resolve(res);
				},
				fail: reject
			})
			break;
			case 'my':
			sdkObj.getAuthUserInfo({
				success: (res) => {
					resolve(res);
				},
				fail: reject
			})
			break;
			default:
			sdkObj.authorize({
				scope: scope,
				success: (res) => {
					resolve(res);
				},
				fail: reject
			})
		}
		
	})
}

//获取微信昵称头像等信息
export function getUserInfo() {
	return new Promise((resolve, reject) => {
		sdkObj.getUserInfo({
			withCredentials:true,
			lang:'zh_CN',
			success: (res) => {
				resolve(res);
			},
			fail: reject
		})
	})
}


//将数据存储在本地缓存中
export function setStorageSync(key, val) {
	switch (sdkName) {
		case 'wx':
		case 'qq':
		case 'mt':
		case 'tt':
			return sdkObj.setStorageSync(key, val)
			break;
		case 'my':
			return sdkObj.setStorageSync({
				'key': key,
				'data': val
			})
			break;
		default:
			return sdkObj.setStorageSync(key, val)
	}
}

//本地缓存中取出数据
export function getStorageSync(key) {
	switch (sdkName) {
		case 'wx':
		case 'qq':
		case 'mt':
		case 'tt':
			return sdkObj.getStorageSync(key)
			break;
		case 'my':
			return sdkObj.getStorageSync({
				'key': key
			}).data
			break;
		default:
			return sdkObj.getStorageSync(key)
	}
}

//客服窗口//TODO::
export function openCustomerService(obj) {
	switch (sdkName) {
		case 'wx':
		case 'qq':
		case 'mt':
		case 'tt':
			return sdkObj.openCustomerServiceConversation(obj)
			break;
		case 'my':
			return sdkObj.openCustomerServiceConversation(obj)
			break;
		default:
			return sdkObj.openCustomerServiceConversation(obj)
	}
}

//拉起支付
export function payment(params) {
	return new Promise((resolve, reject) => {
		switch (sdkName) {
			case 'wx':
				if(params.prop_id){
					sdkObj.requestMidasPaymentGameItem({
						signData:params.signData,
						paySig:params.paySig,
						signature:params.signature,
						success: (res) => {
							resolve(res);
						},
						fail: (err) => {
							if(err.errCode=='-2' || err.errCode=='1' || err.errCode=='7'){
								reject({
									action:'CANCEL',
									errCode:err.errCode || '',
									errMsg:err.errMsg || ''
								})
							}else{
								reject({
									action:'FAIL',
									errCode:err.errCode || '',
									errMsg:err.errMsg || ''
								})
							}
						}
					})
				}else{
					sdkObj.requestMidasPayment({
						mode:params.mode || 'game',
						env:params.env || '0',
						offerId:params.offerId,
						currencyType:params.currencyType,
						platform:params.platform || 'android',
						buyQuantity:params.buyQuantity,
						zoneId:params.zoneId,
						outTradeNo:params.outTradeNo,
						success: (res) => {
							resolve(res);
						},
						fail: (err) => {
							if(err.errCode=='-2' || err.errCode=='1' || err.errCode=='7'){
								reject({
									action:'CANCEL',
									errCode:err.errCode || '',
									errMsg:err.errMsg || ''
								})
							}else{
								reject({
									action:'FAIL',
									errCode:err.errCode || '',
									errMsg:err.errMsg || ''
								})
							}
						}
					})
				}
				break;
			case 'qq':
				sdkObj.requestMidasPayment({
					prepayId:params.prepayId,
					starCurrency:params.buyQuantity || params.amt,
					setEnv:params.env || 0,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						if(err.errCode=='-2'){
							reject({
								action:'CANCEL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}else{
							reject({
								action:'FAIL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}
					}
				})
				break;
			case 'my':
				if(params.platform==='ios'){
					if(sdkObj.requestGamePayCoinPayment) {
						sdkObj.requestGamePayCoinPayment({
							buyQuantity: params.buyQuantity,
							zoneId: params.zoneId,
							goodsName: params.title,
							customId: params.outTradeNo,
							extraInfo: JSON.parse(params.extraInfo),
							success: (res) => {
								resolve(res);
							},
							fail: (err) => {
								if(err.errCode==='60005'){
									reject({
										action:'CANCEL',
										errCode:err.error || '',
										errMsg:err.errorMessage || ''
									})
								}else{
									reject({
										action:'FAIL',
										errCode:err.error || '',
										errMsg:err.errorMessage || ''
									})
								}
							},
						});
					}else{
						reject({
							action:'FAIL',
							errCode:15204,
							errMsg:'接口不可用，仅支付宝10.7.26及以上版本支持，充值功能受限'
						})
					}
				}else{
					sdkObj.requestGamePayment({
						buyQuantity:params.buyQuantity,
						customId:params.outTradeNo,
						extraInfo:params.extraInfo,
						success: (res) => {
							resolve(res);
						},
						fail: (err) => {
							if(err.errCode==='6001'){
								reject({
									action:'CANCEL',
									errCode:err.error || '',
									errMsg:err.errorMessage || ''
								})
							}else{
								reject({
									action:'FAIL',
									errCode:err.error || '',
									errMsg:err.errorMessage || ''
								})
							}
						}
					})
				}
				break;
			case 'mt':
				sdkObj.requestMidasPayment({
					mgcId:params.mgcId,
					appId:params.appId,
					accessToken:params.accessToken,
					bizOrderNo:params.outTradeNo,
					productId:params.prop_id,
					productName:params.productName || '',
					productDesc:params.productDesc || '',
					productUrl:params.productUrl || '',
					needRefresh:params.needRefresh || '0',
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						if(err.errCode=='1001'){
							reject({
								action:'CANCEL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}else{
							reject({
								action:'FAIL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}
					}
				})
			case 'tt':
				sdkObj.requestGamePayment({
					mode:params.mode || 'game',
					env:params.env || '0',
					currencyType:params.currencyType,
					platform:params.platform || 'android',
					buyQuantity:params.buyQuantity,
					zoneId:params.zoneId || '1',
					customId:params.outTradeNo,
					extraInfo:params.extraInfo,
					success: (res) => {
						resolve(res);
					},
					fail: (err) => {
						if(err.errCode=='-2'){
							reject({
								action:'CANCEL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}else{
							reject({
								action:'FAIL',
								errCode:err.errCode || '',
								errMsg:err.errMsg || ''
							})
						}
					}
				})
			case 'jd':
				sdkObj.navigateToNative({
					dataParam: {
						url: "openapp.jdmobile://virtual", // 固定写法
						params: {
						  category: "jump",
						  url: params.jd_h5_pay_url, // 业务支付h5页面地址
						  des: "m",
						  param: {}, // 为空时也要传此字段
						},
					},
					success(res) {
				        resolve(res);
					},
					fail(res) {
						reject(res)
					},
				});
				break;
			default:
				sdkObj.requestMidasPayment(params)
		}
	})
}

//预览二维码
export function previewQrCode(params){
	switch (sdkName) {
		case 'wx':
		case 'qq':
		case 'mt':
		case 'tt':
			return sdkObj.previewImage({
				current: params,
				urls: [params], // 需要预览的图片http链接列表
			})
			break;
		case 'my':
			return sdkObj.previewImage({
				current: 0,
				urls: [params], // 需要预览的图片http链接列表
				enablesavephoto:true,
				enableShowPhotoDownload:true
			})
			break;
		default:
			return sdkObj.previewImage({
				current: params,
				urls: [params], // 需要预览的图片http链接列表
			})
	}
}

//设置系统剪贴板的内容。调用成功后，会弹出 toast 提示"内容已复制"
export function setClipboardContent(params){
	return new Promise((resolve, reject) => {
		switch (sdkName) {
			case 'wx':
			case 'qq':
			case 'mt':
			case 'tt':
				sdkObj.setClipboardData({
					data: params,
					success: (res) => {
						resolve(res);
					},
					fail: reject
				})
				break;
			case 'my':
			console.log(params)
				return sdkObj.setClipboard({
					'text':params,
					success: (res) => {
						resolve(res);
					},
					fail: reject
				})
				break;
			default:
				sdkObj.setClipboardData({
					data: params,
					success: (res) => {
						resolve(res);
					},
					fail: reject
				})
		}
	})
}


//分享小游戏
export function shareMiniGame(params){
	params.query.user_id = getStorageSync('user_id');
	let queryStr = Object.keys(params.query).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params.query[key])).join('&');
	switch (sdkName) {
		case 'my':
			sdkObj.onShareAppMessage =  function () {
				return {
					title: params.title,
					desc: params.desc || params.title,
					query: queryStr,
				}
			}
			sdkObj.showSharePanel({});
		default:
			params.query = queryStr;
			return sdkObj.shareAppMessage({
				...params
			});
	}
}

//监听分享
export function onShareMiniGame(params){
	params.query.user_id = getStorageSync('user_id');
	let queryStr = Object.keys(params.query).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params.query[key])).join('&');
	switch (sdkName) {
		case 'my':
			sdkObj.onShareAppMessage =  function () {
				return {
					title: params.title,
					desc: params.desc || params.title,
					query: queryStr,
				}
			}
			sdkObj.showSharePanel({});
		default:
			params.query = queryStr;
			sdkObj.onShareAppMessage(() => {
				return {...params}
			});
	}
}

// 跳转到小程序
export function navigateToMiniProgram(params) {
   switch (sdkName) {
      case 'my':
         sdkObj.navigateToMiniProgram({
            appId: params.appId,
            path: params.path,
         })
         break;
      default:
         break;
   }
}


//封装签名方法
export function getSign(data) {
	data = objKeySort(data);
	let signStr = "";
	for (let key in data) {
		if (data[key] == null || data[key] == 'null' || data[key] == 'NULL' || data[key] == '' || data[key] ==
			undefined || data[key] == 'undefined') {
			delete data[key]; // 参数值为空，就删除这个属性
		} else {
			let val = data[key]
			signStr += key + '=' + val + '&'
		}
	}
	//signStr = signStr.slice(0,-1);
	let signKey = require('../config.js').secret;
	if (require('../config.js').deBug) {
		//console.log('signStr:' + signStr + 'key=' + signKey)
	}
	let md5res = md5(signStr + 'key=' + signKey)
	return md5res;
}


//对象按照key从低到高排序;
export function objKeySort(obj) {
	var sortArry = new Array;
	var keysArr = Object.keys(obj).sort(); //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序
	var newObj = {}; //创建一个新的对象，用于存放排好序的键值对
	for (var i in keysArr) {
		//newObj[keysArr[i]] = obj[keysArr[i]]; 
		newObj[keysArr[i]] = encodeURIComponent(obj[keysArr[i]]); //向新创建的对象中按照排好的顺序依次增加键值对
	}
	return newObj; //返回排好序的新对象
}